package com.greendragon.web.action.account; 

import java.util.Date;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.greendragon.control.constant.GlobalConstants;
import com.greendragon.persistence.domain.User;
import com.greendragon.persistence.enmu.UserRoleType;
import com.greendragon.service.frontend.IUserFrontendService;
import com.greendragon.util.EncryptionUtil;
import com.greendragon.web.action.BaseAction;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;

/** 
 * @author wulibin, exceptsky@gmail.com, 2011-11-13 上午10:12:09
 * 
 */
public class RegisterAction extends BaseAction{

	private static final long serialVersionUID = -5002428870829195531L;
	private static Logger          logger           = Logger.getLogger(RegisterAction.class);
	
	private IUserFrontendService   				userService;
	private ImageCaptchaService    				captchaService;
	
	private String 					captcha;
	private String 					token;
	
    private String                 	name;                                   	// 用户名
    private String                 	password;                                	// 密码
    private String                 	confirmPassword;                         	// 确认密码
    private String                 	displayName;                             	// 显示昵称

    private String                 	ajaxValue;                               	// ajax Email验证值
    private String                 	ajaxName;                                	// ajax Email验证参数名
    private String                 	ajaxResult;                              	// ajax Email验证返回信息
    
    public String execute() throws Exception {
    	
        User user = userService.getByName(name);
        if (null != user) {
            // 该email已经被注册
            addFieldError("name", getText("register.email.fail"));
            return INPUT;
        } else {
            user = new User();
            user.setName(name);
            user.setPassword(password);
            user.setDisplayName(displayName);
            user.setEmail(name);
            user.setActive(true);
            user.setBlock(false);
    		user.setCreatedAt(new Date());
    		user.setLastLoginAt(new Date());
            user.setCreatedIp(getRequest().getRemoteHost());
            user.setLastLoginIp(getRequest().getRemoteHost());
            user.setRole(UserRoleType.USER.getName());
            user.setGravatarHash(EncryptionUtil.encodeMD5(user.getEmail()));
            userService.register(user);
            getSession().put(GlobalConstants.SESSION_LOGIN_USER, user);
            return SUCCESS;
        }
    }
    
    @SkipValidation
    public String asyncNameCheck() {
        if (null == ajaxName || !ajaxName.equals("name") || null == ajaxValue || null != userService.getByName(ajaxValue)) {
        	ajaxResult = getText("register.email.fail");
        } else {
        	ajaxResult = "y";
        }
        return SUCCESS;
    }
    
    public void validate() {
    	//已经有错误，就不再校验
    	if(getFieldErrors().size()!=0){
    		return;
    	}
    	if(token!=null){
        	//校验验证码
   		 Boolean isResponseCorrect = Boolean.FALSE;
            try {
                isResponseCorrect = captchaService.validateResponseForID(token,captcha.toUpperCase());
            } catch (CaptchaServiceException e) {
           	 logger.error(e);
           	 addFieldError("captcha", "captcha.fail");
           	 return;
            }
            
            if(!isResponseCorrect){
           	 addFieldError("captcha", "captcha.fail");
            }
    	}else{
    		addFieldError("captcha", "captcha.fail");
    	}
    }

	public void setUserService(IUserFrontendService userService) {
		this.userService = userService;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}
	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}

	public void setAjaxName(String ajaxName) {
		this.ajaxName = ajaxName;
	}

	public void setAjaxValue(String ajaxValue) {
		this.ajaxValue = ajaxValue;
	}
	
	public void setAjaxResult(String ajaxResult) {
		this.ajaxResult = ajaxResult;
	}

	public String getAjaxResult() {
		return ajaxResult;
	}

	public String getName() {
		return name;
	}

	public String getDisplayName() {
		return displayName;
	}

	public void setCaptchaService(ImageCaptchaService captchaService) {
		this.captchaService = captchaService;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getCaptcha() {
		return captcha;
	}

	public String getPassword() {
		return password;
	}
	
}
 